package com.vinobase.controller.administration;


import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyFactory;
import com.vinobase.model.bean.Category;
import com.vinobase.utils.ResourceNotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.portlet.ModelAndView;


import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.List;

@Controller
public class CategoryController {

    @Autowired
    private ObjectifyFactory objectifyFactory;

    @RequestMapping(value="/administration/category/create.html", method=RequestMethod.GET)
    protected String getCreateForm(Model model){
        model.addAttribute(new Category());
        return "administration/category/create";
    }

    @RequestMapping(value="/administration/category/list.html")
    protected String getList(Model model) {

        Objectify ofy = objectifyFactory.begin();
        List<Category> categories = ofy.query(Category.class).list();
        model.addAttribute("categories", categories);
        return "administration/category/list";
    }

    @RequestMapping(value="administration/category/create.html", method=RequestMethod.POST)
    protected String create(@Valid Category category, BindingResult result, Model model){
        if (result.hasErrors()) {
                    return "administration/category/create";
        }
        Objectify ofy = objectifyFactory.begin();
        ofy.put(category);

        return getList(model);
    }

    @RequestMapping(value="administration/category/{id}.html", method=RequestMethod.GET)
    protected String view(@PathVariable Long id, Model model){
        Objectify ofy = objectifyFactory.begin();
        Category cat = ofy.get(Category.class, id);
        if(cat == null) {
            throw new ResourceNotFoundException(id);
        }
        model.addAttribute(cat);
        return "administration/category/create";

    }

    @RequestMapping(value="administration/category/delete.html", method=RequestMethod.GET)
    protected String delete(HttpServletRequest request, Model model){

        Objectify ofy = objectifyFactory.begin();
        ofy.delete(Category.class, Long.parseLong(request.getParameter("id")));

        return getList(model);

    }





}
